<?php
/**
 ***********************************************************************************************************************
 * 国通接口统一基础类
 * @author ldh
 ***********************************************************************************************************************
 */

namespace soa\partner\gt;

use artisan\http;

class GtClient
{
    const LOGIN_URL = 'http://101.227.81.110:8013/AppLoginApi/api/AppLogin';//正式地址

//    const UPLOAD_URL = 'http://101.227.81.122:8080/gto365/scanDataAction';//测试地址
    const UPLOAD_URL = 'http://101.227.81.120:8080/gto365/scanDataAction';//正式地址

    const LOGIN_KEY = 'a4915c81f7ebdca6';

    protected $service_name = 'gto_api';

    protected $_timeout = 5;

    /**
     * 国通统一登录接口
     *
     * @param array $account 账号信息
     * @param int $type 操作类型(1:绑定 2:登陆)
     * @return bool|mixed
     */
    public final function login(array $account, $type = 2)
    {
        $empNo      = $account['cm_code'];
        $cmPhone    = $account['binding_phone'];
        $branchCode = $account['branch_code'];

        if(empty($empNo) || empty($cmPhone) || empty($branchCode)){
            return false;
        }

        if(1 == $type){
            $empPwd = $account['cm_pwd'];
            if(empty($empPwd)){
                return false;
            }
        }else{
            $empPwd = '';
        }

        $this->api = 'AppLogin';
        $url = self::LOGIN_URL;

        $post = [
            'OrgCode'  => $branchCode,
            'UserCode' => $empNo,
            'PassWord' => $empPwd,
            'TelNum'   => $cmPhone,
            'type'     => $type,
            'key'      => md5(self::LOGIN_KEY . date('Ymd')),
        ];

        $options = [
            'TIMEOUT'    => 5,
            'HTTPHEADER' => [
                'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
            ],
        ];

        return $this->request($url, $post, $options, 'Success','Message','Result');
    }

    public final function upload($waybillType, $scanData)
    {
        $options = [
            'TIMEOUT'    => 5,
            'HTTPHEADER' => [
                'Content-Type: application/json;charset=UTF-8',
            ],
        ];

        $scanData = json_encode(['list'=>$scanData]);

        return $this->request($this->getUploadUrl($waybillType), $scanData, $options, 'success', 'msg', 'success');
    }

    /**
     * @param $type
     * @return string
     */
    public function getUploadUrl($type)
    {
        switch($type){
            case 1://收件
                $this->api = 'ajaxInsertListSJ';
                break;
            case 2://派件
                $this->api = 'ajaxInsertListPJ';
                break;
            case 3://签收
                $this->api = 'ajaxInsertListQS';
                break;
            default:
                raise(1009);
        }

        return self::UPLOAD_URL . '!' . $this->api . '.action';
    }

    protected $api = 'gt_api';

    protected $msg = '';

    protected $code = 0;

    protected $data = '';

    protected $result = '';

    /**
     * @return string
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @return string
     */
    public function getMsg()
    {
        return $this->msg;
    }

    /**
     * @return string
     */
    public function getResult()
    {
        return $this->result;
    }

    /**
     * @param array $result
     */
    protected function _reset($result = [])
    {
        $this->result = $result;
        $this->data = '';
        $this->code = 0;
        $this->msg = '';
    }

    protected $requestType = 'post';

    /**
     * @param $url
     * @param $data
     * @param array $options
     * @param string $status
     * @param string $msg
     * @param string $result
     * @return string
     */
    protected function request($url, $data, $options = [], $status = 'success', $msg = 'msg', $result = 'data')
    {
        $time1 = time();

        if('get' == $this->requestType){
            $response = http::get($url, $data, $options);
        }else{
            $response = http::post($url, $data, $options);
        }

        $this->result = $response;

        $this->parse($response, $status, $msg, $result);

        if($this->code && $this->code < 1009) {
            $msg = 'result：'.$this->getResult() . '耗时：'.(time()-$time1).'。request:'.(is_array($data)?json_encode($data,JSON_UNESCAPED_UNICODE):$data);
            logDebug($msg, $this->api, $this->service_name);
        }

        return $this->data;
    }

    /**
     * @param $result
     * @param string $status
     * @param string $msg
     * @param string $data
     */
    protected function parse($result, $status = 'success', $msg = 'msg', $data = 'data')
    {
        $this->_reset($result);

        if(empty($result)) {
            $this->msg = '网络忙，请稍后重试[该服务或接口无返回]!';
            $this->code = 1000;
            return;
        }

        $arr = json_decode($result, true);
        if(json_last_error() != 0) {
            $this->msg = '该服务或接口返回结果无法解析:' . json_last_error() . (string)json_last_error_msg();
            $this->code = 422;
            return;
        }

        if(!isset($status)) {
            $this->msg = !empty($arr[$msg]) ? $arr[$msg] : '该服务或接口返回未知状态错误!';
            $this->code = 422;
            return;
        }

        if(isset($arr[$data])) {
            $this->data = $arr[$data];
        }

        //业务错误
        if('false' == $arr[$status] || false === $arr[$status]) {
            $this->msg = !empty($arr[$msg]) ? $arr[$msg] : '请求出错!';
            $this->code = 1020;
            return;
        }

        return;
    }
}